<?php
class Languages extends Dao
{
	private static $_instance = null;
	protected $_db = null, $_cache = null;
	
	protected function __construct()
	{
		parent::__construct();
	}
	
	public static function getInstance() 
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
	
	public function getList(array $args = array(), $intPage = 1, $intLimit = MIN_ROWS_PER_PAGE)
	{
		try{
			$defaults = array(
			);
			$args = $this->args_merge($defaults, $args);
			
			$intStart = ($intPage-1)*$intLimit;
			
			$cmd = $this->_db->createCommand('SELECT SQL_CALC_FOUND_ROWS * 
													 FROM tbl_languages
													 LIMIT :intStart, :intLimit');
			$cmd->bindParam(":intStart",$intStart,PDO::PARAM_INT);
			$cmd->bindParam(":intLimit",$intLimit,PDO::PARAM_INT);		
			$arrResults = $cmd->queryAll();
			if(!empty($arrResults)){
				$arrResults[0]['total_rows'] = $this->_db->createCommand('SELECT FOUND_ROWS();')->queryScalar();
			}
			return $arrResults;
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function get($id)
	{
		try{
			return $arrResults = $this->_db->createCommand()->select('*')
														  	->from('tbl_languages')
														  	->where("language_id=:id", array(":id"=>$id))
														  	->queryRow();
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function insert(array $args)
	{		
		try{
			$defaults = array(
				'language_code' => null,
				'language_name' => null,
				'language_nativename' => null,
				'language_direction' => null,
				'language_description' => null,
				'language_default' => null
			);
			$args = $this->args_merge($defaults, $args);
			
			$cmd = $this->_db->createCommand();
			$cmd->insert('tbl_languages',$args);
			return Yii::app()->db->getLastInsertId();
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function update($id, array $args)
	{		
		try{
			$defaults = array(
				'language_code' => null,
				'language_name' => null,
				'language_nativename' => null,
				'language_direction' => null,
				'language_description' => null,
				'language_default' => null		
			);
			$args = $this->args_merge($defaults, $args);
			
			$cmd = $this->_db->createCommand();
			return $cmd->update('tbl_languages',$args, 'language_id=:id', array(':id'=>$id));
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function delete($id){
		try{
			$cmd = $this->_db->createCommand();
			return $cmd->delete('tbl_languages', 'language_id=:id', array(':id'=>$id));			
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
}